package com.example.spring.boot.rabbitmq.service.impl;

import com.example.spring.boot.rabbitmq.configure.DemoConfirmCallBack;
import com.example.spring.boot.rabbitmq.configure.DemoReturnedCallback;
import com.example.spring.boot.rabbitmq.dto.OrderCreateDTO;
import com.example.spring.boot.rabbitmq.service.OrderService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Exchange xExchange;

    @Autowired
    private TopicExchange topicExchange;

    @Autowired
    private DemoConfirmCallBack demoConfirmCallBack;


    @Autowired
    private DemoReturnedCallback demoReturnedCallback;

    @Override
    public String createOrder(Long userId) {
        String orderNo = System.currentTimeMillis() + new Random(100).nextInt() + "";
        System.out.println("用户：" + userId + "已经创建了订单" + orderNo);
        OrderCreateDTO createDTO = new OrderCreateDTO();
        createDTO.setUserId(userId);
        createDTO.setOrderNo(orderNo);
        this.rabbitTemplate.setConfirmCallback(demoConfirmCallBack);
        this.rabbitTemplate.setReturnsCallback(demoReturnedCallback);
        this.rabbitTemplate.convertAndSend(topicExchange.getName(), "order.create",
                createDTO, new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        System.out.println("发送下单消息=" + new String(message.getBody()));
                        return message;
                    }
                }, new CorrelationData(System.currentTimeMillis() + ""));
        return orderNo;
    }
}
